package com.wangzhen.codebase;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class MyFirstThreadPool {

    private final List<Thread> threadList;
    private final BlockingQueue<Runnable> blockingQueue;

    public MyFirstThreadPool(Integer poolSize, BlockingQueue<Runnable> blockingQueue) {
        this.blockingQueue = blockingQueue;
        threadList = new ArrayList<>(poolSize);
        for (int i = 0; i < poolSize; i++) {
            Thread thread = new WorkThread();
            thread.start();
            threadList.add(thread);
        }
    }

    public void execute(Runnable runnable) throws InterruptedException {
        this.blockingQueue.put(runnable);
    }

    private class WorkThread extends Thread {
        @Override
        public void run() {
            try {
                while (true) {
                    System.out.printf("thread name=%s 开始执行\n1```", Thread.currentThread().getName());
                    Runnable runnable = blockingQueue.take();
                    runnable.run();
                }
            } catch (Exception e) {
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyFirstThreadPool threadPool = new MyFirstThreadPool(2, new ArrayBlockingQueue<>(5));







        threadPool.execute(()-> {
            System.out.println("hello world");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        threadPool.execute(()-> {
            System.out.println("hello china");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        Thread.sleep(10000);
    }


}
